package com.company.netty2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @description: 粘包拆包情况-服务端 解决方法
 * @author: ruoan
 * @date: 2021/1/1 15:53
 */
@Slf4j
public class TimeServerHandlerWithDecoder extends ChannelInboundHandlerAdapter {

    private int counter;



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = (String) msg;
        System.out.println("The time server receive order:"+ body + " the counter is: "+ ++counter);

        //ByteBuf buf = (ByteBuf) msg;
        //byte[] bytes = new byte[buf.readableBytes()];
        //buf.readBytes(bytes);
        //String s = new String(bytes, CharsetUtil.UTF_8).substring(0,bytes.length-System.getProperty("line.separator").length());
        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
        currentTime = currentTime + System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("ex");
        ctx.close();
    }
}
